<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>学生信息</title>
  </head>
  <body>
    <h1>学生管理</h1>
    <form class="layui-form" lay-filter="searchForm">
      <div class="layui-form-item">
        <div class="layui-input-inline" style="width: 80px">
          <button id="addBtn" type="button" class="layui-btn">
            <i class="layui-icon"></i>
          </button>
        </div>
        <div class="layui-input-inline" style="width: 80px">
          <select name="type">
            <option value="">所有</option>
            <option value="name">姓名</option>
            <option value="gender">性别</option>
            <option value="age">年龄</option>
          </select>
        </div>
        <div class="layui-input-inline">
          <input
            type="text"
            name="value"
            placeholder="请输入搜索内容"
            autocomplete="off"
            class="layui-input"
          />
        </div>
        <div class="layui-input-inline">
          <button type="button" id="searchBtn" class="layui-btn">
            <i class="layui-icon layui-icon-search"></i>
          </button>
        </div>
      </div>
    </form>
    <table id="studentTable" lay-filter="studentTable"></table>
    <script type="text/html" id="studentBar">
      <a class="layui-btn layui-btn-xs" lay-event="edit">编辑</a>
      <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del"
        >删除</a
      >
    </script>
    <script>
      layui.define(function () {
        let $ = layui.$;
        let table = layui.table;
        let form = layui.form;
        
        form.render();
        table.render({
          elem: "#studentTable",
          url: "/students", //数据接口
          page: {
            //支持传入 laypage 组件的所有参数（某些参数除外，如：jump/elem） - 详见文档
            layout: ["limit", "count", "prev", "page", "next", "skip"], //自定义分页布局
            //,curr: 5 //设定初始在第 5 页
            groups: 5, //只显示 5 个连续页码
            first: "首页", //不显示首页
            last: "尾页", //不显示尾页
            limits: [1, 3, 5, 10, 15, 20],
            limit: 3,
          },
          cols: [
            [
              //表头
              { field: "name", title: "姓名" },
              { field: "gender", title: "性别", sort: true },
              { field: "age", title: "年龄", sort: true },
              { field: "cls", title: "所属班级",
              templet: function(d){
                console.log(d);
                return d.cls ? d.cls.name : '';
              }},
              { fixed: "right", title: "操作", toolbar: "#studentBar" },
            ],
          ],
          parseData: function (res) {
            //res 即为原始返回的数据
            return {
              code: 0, //解析接口状态
              msg: "", //解析提示文本
              count: res.total, //解析数据长度
              data: res.rows, //解析数据列表
            };
          },
          request: {
            pageName: "current", //页码的参数名称，默认：page
            limitName: "size", //每页数据量的参数名，默认：limit
          },
        });

        $("#addBtn").click(function () {
          // 弹出增加学生的窗口
          layer.open({
            type: 1,
            title: "增加学生", //不显示标题栏
            area: "300px;",
            shade: 0.6,
            id: "LAY_layuipro", //设定一个id，防止重复弹出
            btn: ["确认", "取消"],
            btnAlign: "c",
            moveType: 1, //拖拽模式，0或者1
            content: `
              <form class="layui-form" lay-filter="addForm">
          <div class="layui-form-item">
            <label class="layui-form-label">姓名</label>
            <div class="layui-input-block">
              <input
                type="text"
                name="name"
                required
                lay-verify="required"
                placeholder="请输入姓名"
                autocomplete="off"
                class="layui-input"
              />
            </div>
          </div>
          <div class="layui-form-item">
            <label class="layui-form-label">年龄</label>
            <div class="layui-input-block">
              <input
                type="text"
                name="age"
                required
                lay-verify="required"
                placeholder="请输入年龄"
                autocomplete="off"
                class="layui-input"
              />
            </div>
          </div>
          <div class="layui-form-item">
            <label class="layui-form-label">性别</label>
            <div class="layui-input-block">
                <input type="radio" name="gender" value="男" title="男">
                <input type="radio" name="gender" value="女" title="女">
            </div>
          </div>
          <div class="layui-form-item">
            <label class="layui-form-label">选择班级</label>
            <div class="layui-input-block">
                <select name="cls">
                  
                </select>
            </div>
          </div>
          </form>
              `,
            yes() {
              console.log("yes", form.val("addForm"));
              $.ajax({
                type: "post",
                url: "/students",
                data: form.val("addForm"),
                success() {
                  table.reload("studentTable");
                },
              });
              layer.closeAll();
            },
            success: function (layero) {
              // 打开增加窗口后执行的回调函数
              $.ajax({
                type:"get",
                url:"/classes/all",
                success(data){
                  let str = ``;
                  for(let cls of data){
                    str += `<option value="${cls._id}">${cls.name}</option>`
                  }
                  $("[name=cls]").html(str);
                  form.render();
                }
              });
              
            },
          });
        });

        //监听行工具事件
        table.on("tool(studentTable)", function (obj) {
          var data = obj.data;
          console.log(obj);
          if (obj.event === "del") {
            layer.confirm("真的删除行么", function (index) {
              $.ajax({
                type: "delete",
                url: "/students/" + data._id,
                success() {
                  layer.close(index);
                  table.reload("studentTable", {
                    page: {
                      curr: 1,
                    },
                  });
                },
              });
            });
          } else if (obj.event === "edit") {
            // 弹出修改学生的窗口
            layer.open({
              type: 1,
              title: "修改学生", //不显示标题栏
              area: "300px;",
              shade: 0.6,
              id: "LAY_layuipro", //设定一个id，防止重复弹出
              btn: ["确认", "取消"],
              btnAlign: "c",
              moveType: 1, //拖拽模式，0或者1
              content: `
              <form class="layui-form" lay-filter="updateForm">
          <div class="layui-form-item">
            <label class="layui-form-label">姓名</label>
            <div class="layui-input-block">
              <input
                type="text"
                name="name"
                required
                lay-verify="required"
                placeholder="请输入姓名"
                autocomplete="off"
                class="layui-input"
              />
            </div>
          </div>
          <div class="layui-form-item">
            <label class="layui-form-label">年龄</label>
            <div class="layui-input-block">
              <input
                type="text"
                name="age"
                required
                lay-verify="required"
                placeholder="请输入年龄"
                autocomplete="off"
                class="layui-input"
              />
            </div>
          </div>
          <div class="layui-form-item">
            <label class="layui-form-label">性别</label>
            <div class="layui-input-block">
                <input type="radio" name="gender" value="男" title="男">
                <input type="radio" name="gender" value="女" title="女">
            </div>
          </div>
          <input type="hidden" id="updateStudentId" name="_id">
          </form>
              `,
              yes() {
                $.ajax({
                  type: "put",
                  url: "/students/" + $("#updateStudentId").val(),
                  data: form.val("updateForm"),
                  success() {
                    table.reload("studentTable");
                  },
                });
                layer.closeAll();
              },
              success: function (layero) {
                // 根据id查询要修改的学生信息，并将学生信息填充到对应的表单项中
                $.ajax({
                  type: "get",
                  url: "/students/" + data._id,
                  success(student) {
                    form.val("updateForm", student);
                    form.render();
                  },
                });
              },
            });
          }
        });

        $("#searchBtn").click(function () {
          console.log(form.val("searchForm"));
          table.reload("studentTable", {
            where: form.val("searchForm"),
            page:{
                 //支持传入 laypage 组件的所有参数（某些参数除外，如：jump/elem） - 详见文档
                layout: ["limit", "count", "prev", "page", "next", "skip"], //自定义分页布局
                //,curr: 5 //设定初始在第 5 页
                groups: 5, //只显示 5 个连续页码
                first: "首页", //不显示首页
                last: "尾页", //不显示尾页
                limits: [1, 3, 5, 10, 15, 20],
                limit: 3,
                curr:1
            }
          });
        });
      });
    </script>
  </body>
</html>
